package com.ecoolex.discount.sales.ws;

import java.time.Instant;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.assertj.core.util.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.ecoolex.discount.sales.core.external.v2.YWExternalService;
import com.ecoolex.discount.sales.core.external.v2.pojo.GetBrandsResponse;
import com.ecoolex.discount.sales.core.manager.YWBrandCateManager;
import com.ecoolex.discount.sales.core.manager.YWBrandManager;
import com.ecoolex.discount.sales.entity.YWBrand;
import com.ecoolex.discount.sales.entity.YWBrandCate;
import com.ecoolex.discount.sales.pojo.GetBrandsDTO;

@Service
public class YWBrandServiceImpl implements YWBrandService {
	@Autowired
	YWBrandManager ywBrandManager;

	@Autowired
	YWBrandCateManager ywBrandCateManager;

	@Autowired
	YWExternalService ywExternalService;

	@Override
	public List<GetBrandsDTO> getAllBrands(String channelId) {
		String token = ywExternalService.getToken(channelId);
		GetBrandsResponse resp = ywExternalService.getBrands(token);
		List<GetBrandsDTO> getBrandsDTOS = Collections.EMPTY_LIST;
		if (Objects.nonNull(resp) && YWExternalService.SUCCESS.equals(resp.getErrno())) {
			List<GetBrandsResponse.Brand> brands = resp.getData();
			if (CollectionUtils.isNotEmpty(brands)) {
				getBrandsDTOS = brands.stream().map(brand -> {
					GetBrandsDTO brandsDTO = new GetBrandsDTO();
					BeanUtils.copyProperties(brand, brandsDTO);
					brandsDTO.setQueryLink(brand.getWebsite());
					if (Objects.nonNull(brand.getUpdateTime()) && brand.getUpdateTime() > 0) {
						brandsDTO.setUpdateTime(Date.from(Instant.ofEpochSecond(brand.getUpdateTime())));
					}
					return brandsDTO;
				}).collect(Collectors.toList());
			}
		}
		return getBrandsDTOS;
	}

	@Override
	public List<GetBrandsDTO> getAllBrandsFromDB(String channelId) {
		List<YWBrand> brands = ywBrandManager.getAllBrands(channelId);
		if (!CollectionUtils.isEmpty(brands)) {
			List<GetBrandsDTO> getBrandsDTOS = brands.stream().map(brand -> {
				GetBrandsDTO brandsDTO = new GetBrandsDTO();
				BeanUtils.copyProperties(brand, brandsDTO);
				List<YWBrandCate> ywBrandCates = ywBrandCateManager.getCateByBrandId(brand.getBrandId());
				if (!CollectionUtils.isEmpty(ywBrandCates)) {
					List<String> cates = ywBrandCates.stream().map(YWBrandCate::getCategroy)
							.collect(Collectors.toList());
					brandsDTO.setCategories(cates);
				}
				brandsDTO.setUpdateTime(brand.getLastModifiedTime());
				return brandsDTO;
			}).collect(Collectors.toList());
			return getBrandsDTOS;
		}
		return Lists.<GetBrandsDTO> emptyList();
	}

}
